// 代码语法高亮和差异对比功能
(function() {
    'use strict';

    // 语法高亮关键词定义
    const SYNTAX_PATTERNS = {
        python: {
            keywords: /\b(def|class|if|elif|else|for|while|try|except|finally|import|from|as|return|yield|lambda|with|pass|break|continue|and|or|not|in|is|None|True|False)\b/g,
            strings: /(["'])((?:\\.|(?!\1)[^\\\r\n])*?)\1/g,
            comments: /#.*$/gm,
            numbers: /\b\d+(?:\.\d+)?\b/g,
            functions: /\b([a-zA-Z_][a-zA-Z0-9_]*)(?=\s*\()/g,
            classes: /\bclass\s+([a-zA-Z_][a-zA-Z0-9_]*)/g
        },
        javascript: {
            keywords: /\b(function|var|let|const|if|else|for|while|do|switch|case|default|try|catch|finally|return|break|continue|new|this|typeof|instanceof|null|undefined|true|false)\b/g,
            strings: /(["'`])((?:\\.|(?!\1)[^\\\r\n])*?)\1/g,
            comments: /\/\/.*$|\/\*[\s\S]*?\*\//gm,
            numbers: /\b\d+(?:\.\d+)?\b/g,
            functions: /\b([a-zA-Z_$][a-zA-Z0-9_$]*)(?=\s*\()/g
        },
        java: {
            keywords: /\b(public|private|protected|static|final|abstract|class|interface|extends|implements|if|else|for|while|do|switch|case|default|try|catch|finally|return|break|continue|new|this|super|null|true|false|void|int|double|float|boolean|String)\b/g,
            strings: /"((?:\\.|[^"\\\r\n])*?)"/g,
            comments: /\/\/.*$|\/\*[\s\S]*?\*\//gm,
            numbers: /\b\d+(?:\.\d+)?[fFdD]?\b/g,
            functions: /\b([a-zA-Z_][a-zA-Z0-9_]*)(?=\s*\()/g,
            classes: /\b(class|interface)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g
        },
        cpp: {
            keywords: /\b(int|double|float|char|bool|void|if|else|for|while|do|switch|case|default|try|catch|return|break|continue|class|struct|public|private|protected|static|const|virtual|override|new|delete|this|nullptr|true|false)\b/g,
            strings: /"((?:\\.|[^"\\\r\n])*?)"/g,
            comments: /\/\/.*$|\/\*[\s\S]*?\*\//gm,
            numbers: /\b\d+(?:\.\d+)?[fF]?\b/g,
            functions: /\b([a-zA-Z_][a-zA-Z0-9_]*)(?=\s*\()/g,
            classes: /\b(class|struct)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g
        },
        typescript: {
            keywords: /\b(function|var|let|const|if|else|for|while|do|switch|case|default|try|catch|finally|return|break|continue|new|this|typeof|instanceof|null|undefined|true|false|class|interface|extends|implements|public|private|protected|static|readonly|abstract|async|await|enum|namespace|type|import|export|from|as|any|string|number|boolean|void|never)\b/g,
            strings: /(["'`])((?:\\.|(?!\1)[^\\\r\n])*?)\1/g,
            comments: /\/\/.*$|\/\*[\s\S]*?\*\//gm,
            numbers: /\b\d+(?:\.\d+)?\b/g,
            functions: /\b([a-zA-Z_$][a-zA-Z0-9_$]*)(?=\s*[<(])/g,
            classes: /\b(class|interface|enum)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g
        },
        lua: {
            keywords: /\b(and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/g,
            strings: /(["'])((?:\\.|(?!\1)[^\\\r\n])*?)\1|\[\[([\s\S]*?)\]\]/g,
            comments: /--.*$|--\[\[[\s\S]*?\]\]/gm,
            numbers: /\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b/g,
            functions: /\b([a-zA-Z_][a-zA-Z0-9_]*)(?=\s*[\(:])/g
        }
    };

    // 应用语法高亮
    function applySyntaxHighlight(element, language) {
        if (!SYNTAX_PATTERNS[language]) {
            return;
        }

        let content = element.textContent;
        const patterns = SYNTAX_PATTERNS[language];

        // 保护字符串和注释，避免嵌套高亮
        const protectedRanges = [];
        
        // 先处理注释
        content = content.replace(patterns.comments, (match, offset) => {
            protectedRanges.push({start: offset, end: offset + match.length});
            return `<span class="comment">${escapeHtml(match)}</span>`;
        });

        // 处理字符串
        content = content.replace(patterns.strings, (match, quote, str, offset) => {
            if (isProtected(offset, protectedRanges)) return match;
            protectedRanges.push({start: offset, end: offset + match.length});
            return `<span class="string">${escapeHtml(match)}</span>`;
        });

        // 处理数字
        content = content.replace(patterns.numbers, (match, offset) => {
            if (isProtected(offset, protectedRanges)) return match;
            return `<span class="number">${match}</span>`;
        });

        // 处理关键词
        content = content.replace(patterns.keywords, (match, offset) => {
            if (isProtected(offset, protectedRanges)) return match;
            return `<span class="keyword">${match}</span>`;
        });

        // 处理函数
        content = content.replace(patterns.functions, (match, funcName, offset) => {
            if (isProtected(offset, protectedRanges)) return match;
            return `<span class="function">${funcName}</span>`;
        });

        // 处理类
        if (patterns.classes) {
            content = content.replace(patterns.classes, (match, keyword, className, offset) => {
                if (isProtected(offset, protectedRanges)) return match;
                return `${keyword} <span class="class">${className}</span>`;
            });
        }

        element.innerHTML = content;
    }

    // 检查位置是否在保护范围内
    function isProtected(offset, protectedRanges) {
        return protectedRanges.some(range => offset >= range.start && offset < range.end);
    }

    // HTML转义
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 生成代码差异对比
    function generateCodeDiff(oldCode, newCode, language) {
        const oldLines = oldCode.split('\n');
        const newLines = newCode.split('\n');
        const diff = computeDiff(oldLines, newLines);
        
        let html = '<div class="code-diff">';
        html += '<div class="code-diff-header">代码差异对比</div>';
        
        let oldLineNum = 1;
        let newLineNum = 1;
        
        diff.forEach(change => {
            if (change.type === 'unchanged') {
                html += `<div class="code-diff-line unchanged">`;
                html += `<span class="code-diff-line-number">${oldLineNum}</span>`;
                html += `<span class="code-diff-line-number">${newLineNum}</span>`;
                html += escapeHtml(change.value);
                html += '</div>';
                oldLineNum++;
                newLineNum++;
            } else if (change.type === 'removed') {
                html += `<div class="code-diff-line removed">`;
                html += `<span class="code-diff-line-number">${oldLineNum}</span>`;
                html += '<span class="code-diff-line-number">-</span>';
                html += escapeHtml(change.value);
                html += '</div>';
                oldLineNum++;
            } else if (change.type === 'added') {
                html += `<div class="code-diff-line added">`;
                html += '<span class="code-diff-line-number">-</span>';
                html += `<span class="code-diff-line-number">${newLineNum}</span>`;
                html += escapeHtml(change.value);
                html += '</div>';
                newLineNum++;
            }
        });
        
        html += '</div>';
        return html;
    }

    // 简单的差异计算算法
    function computeDiff(oldLines, newLines) {
        const diff = [];
        let i = 0, j = 0;
        
        while (i < oldLines.length || j < newLines.length) {
            if (i >= oldLines.length) {
                diff.push({type: 'added', value: newLines[j]});
                j++;
            } else if (j >= newLines.length) {
                diff.push({type: 'removed', value: oldLines[i]});
                i++;
            } else if (oldLines[i] === newLines[j]) {
                diff.push({type: 'unchanged', value: oldLines[i]});
                i++;
                j++;
            } else {
                // 简单处理：先删除再添加
                diff.push({type: 'removed', value: oldLines[i]});
                diff.push({type: 'added', value: newLines[j]});
                i++;
                j++;
            }
        }
        
        return diff;
    }

    // 创建代码版本历史展示
    function createVersionHistory(versions) {
        let html = '<div class="code-version-history">';
        
        versions.forEach((version, index) => {
            html += '<div class="code-version-item">';
            html += '<div class="code-version-header">';
            html += `<div class="code-version-info">版本 ${version.version_number}</div>`;
            html += `<div class="code-version-date">${version.created_at}</div>`;
            html += '</div>';
            
            if (version.commit_message) {
                html += `<div class="code-version-message">${escapeHtml(version.commit_message)}</div>`;
            }
            
            html += '<div class="code-version-stats">';
            html += `文件大小: ${version.file_size} 字节`;
            if (index > 0) {
                html += ` | <a href="#" class="code-preview-btn" onclick="showVersionDiff(${index}, ${index-1})">与上一版本对比</a>`;
            }
            html += '</div>';
            html += '</div>';
        });
        
        html += '</div>';
        return html;
    }

    // 增强代码预览
    function enhanceCodePreview(element, language, content) {
        const container = document.createElement('div');
        container.className = 'code-preview-container';
        
        // 创建工具栏
        const toolbar = document.createElement('div');
        toolbar.className = 'code-preview-toolbar';
        toolbar.innerHTML = `
            <div class="code-preview-language">${language.toUpperCase()}</div>
            <div class="code-preview-actions">
                <button class="code-preview-btn" onclick="copyCode(this)">复制</button>
                <button class="code-preview-btn" onclick="toggleFullscreen(this)">全屏</button>
            </div>
        `;
        
        // 创建代码容器
        const codeContainer = document.createElement('div');
        codeContainer.className = `code-highlight ${language}`;
        codeContainer.textContent = content;
        
        container.appendChild(toolbar);
        container.appendChild(codeContainer);
        
        // 替换原元素
        element.parentNode.replaceChild(container, element);
        
        // 应用语法高亮
        applySyntaxHighlight(codeContainer, language);
        
        return container;
    }

    // 复制代码功能
    window.copyCode = function(button) {
        const codeElement = button.closest('.code-preview-container').querySelector('.code-highlight');
        const text = codeElement.textContent;
        
        navigator.clipboard.writeText(text).then(() => {
            const originalText = button.textContent;
            button.textContent = '已复制';
            setTimeout(() => {
                button.textContent = originalText;
            }, 2000);
        }).catch(() => {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            
            const originalText = button.textContent;
            button.textContent = '已复制';
            setTimeout(() => {
                button.textContent = originalText;
            }, 2000);
        });
    };

    // 全屏切换功能
    window.toggleFullscreen = function(button) {
        const container = button.closest('.code-preview-container');
        if (container.classList.contains('fullscreen')) {
            container.classList.remove('fullscreen');
            button.textContent = '全屏';
        } else {
            container.classList.add('fullscreen');
            button.textContent = '退出全屏';
        }
    };

    // 版本差异对比
    window.showVersionDiff = function(codeId, version1, version2) {
        // 创建模态框显示差异
        const modal = createDiffModal();
        document.body.appendChild(modal);
        
        // 显示加载状态
        const content = modal.querySelector('.diff-modal-content');
        content.innerHTML = '<div class="loading">正在加载版本差异...</div>';
        
        // 获取版本差异数据
        const url = `/admin/codes/code/version-diff/${codeId}/${version1}/${version2}/`;
        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const diffHtml = generateCodeDiff(
                        data.version2.content, 
                        data.version1.content, 
                        data.language
                    );
                    
                    content.innerHTML = `
                        <div class="diff-header">
                            <h3>代码版本差异对比</h3>
                            <div class="version-info">
                                <div class="version-item">
                                    <strong>版本 ${data.version2.number}</strong>
                                    <span>${data.version2.created_at}</span>
                                    ${data.version2.commit_message ? `<div class="commit-msg">${data.version2.commit_message}</div>` : ''}
                                </div>
                                <div class="version-item">
                                    <strong>版本 ${data.version1.number}</strong>
                                    <span>${data.version1.created_at}</span>
                                    ${data.version1.commit_message ? `<div class="commit-msg">${data.version1.commit_message}</div>` : ''}
                                </div>
                            </div>
                        </div>
                        ${diffHtml}
                    `;
                } else {
                    content.innerHTML = '<div class="error">加载版本差异失败</div>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                content.innerHTML = '<div class="error">加载版本差异时发生错误</div>';
            });
    };
    
    // 创建差异对比模态框
    function createDiffModal() {
        const modal = document.createElement('div');
        modal.className = 'diff-modal';
        modal.innerHTML = `
            <div class="diff-modal-overlay"></div>
            <div class="diff-modal-container">
                <div class="diff-modal-header">
                    <button class="diff-modal-close">&times;</button>
                </div>
                <div class="diff-modal-content"></div>
            </div>
        `;
        
        // 添加关闭事件
        modal.querySelector('.diff-modal-close').addEventListener('click', () => {
            document.body.removeChild(modal);
        });
        
        modal.querySelector('.diff-modal-overlay').addEventListener('click', () => {
            document.body.removeChild(modal);
        });
        
        return modal;
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 查找所有需要语法高亮的代码块
        const codeBlocks = document.querySelectorAll('[data-language]');
        codeBlocks.forEach(block => {
            const language = block.getAttribute('data-language');
            const content = block.textContent;
            enhanceCodePreview(block, language, content);
        });
        
        // 为现有的代码预览添加语法高亮
        const existingCodeBlocks = document.querySelectorAll('div[style*="font-family: monospace"], div[style*="font-family: \'Courier New\'"');
        existingCodeBlocks.forEach(block => {
            // 尝试从上下文推断语言
            const language = inferLanguageFromContext(block);
            if (language) {
                block.classList.add('code-highlight', language);
                applySyntaxHighlight(block, language);
            }
        });
    });

    // 从上下文推断编程语言
    function inferLanguageFromContext(element) {
        // 查找页面中的语言信息
        const languageElements = document.querySelectorAll('[class*="language"], [data-language]');
        for (let el of languageElements) {
            const lang = el.className.match(/language-(\w+)/) || el.getAttribute('data-language');
            if (lang) {
                return lang.replace('language-', '').toLowerCase();
            }
        }
        
        // 从URL或表单字段推断
        const urlMatch = window.location.href.match(/language=([^&]+)/);
        if (urlMatch) {
            return urlMatch[1].toLowerCase();
        }
        
        // 默认返回python
        return 'python';
    }

})();